import re
import urllib2


def fetch(i):
    txheader={'range':'bytes=%d-%d'%(i,i),'Authorization':'Basic YnV0dGVyOmZseQ=='}
    print "getting range bytes=%d-%d"%(i,i)
    req=urllib2.Request('http://www.pythonchallenge.com/pc/hex/unreal.jpg',None,txheader)
    h=urllib2.urlopen(req)
    print h.headers
    f=open('%d.data'%i,'wb')
    s=h.read()
    f.write(s)
    f.close()
    range2 = h.headers['content-range']
    print "range2 is %s"%range2
    m=re.match(r'bytes \d+-(?P<range>\d+)/\d+',range2)
    j=int(m.group('range'))+1
    if len(s) < 1024:
        print s
    return j


def main():
    i=0
    while True:
        try:
            i=fetch(i)
        except Exception,e:
            print e
            break
